package interpreter

import (
	"io"
	"fmt"
	"reflect"
	"io/ioutil"
	"kumachan/interpreter/lang/textual/scanner"
	"kumachan/interpreter/lang/textual/syntax"
	"kumachan/interpreter/lang/textual/parser"
	"kumachan/interpreter/lang/textual/transformer"
	"kumachan/standalone/util/richtext"
)


func DebugParser(file io.Reader, name string, root string) {
	var code_bytes, e = ioutil.ReadAll(file)
	if e != nil { panic(e) }
	var code_string = string(code_bytes)
	var code = ([] rune)(code_string)
	var tokens, info, _, s_err = scanner.Scan(code)
	if s_err != nil { panic(s_err) }
	fmt.Println("Tokens:")
	for i, token := range tokens {
		fmt.Printf(
			"(%v) at [%v, %v](%v, %v) %v: %v\n",
			i,
			token.Span.Start,
			token.Span.End,
			info[token.Span.Start].Row,
			info[token.Span.Start].Col,
			syntax.Id2Name(token.Id),
			string(token.Content),
		)
	}
	var _, exists = syntax.Name2Id(root)
	if !exists {
		panic("invalid root syntax unit " + root)
	}
	var tree, err = parser.Parse(code, root, name)
	fmt.Println("------------------------------------------------------")
	fmt.Println("CST Nodes:")
	parser.PrintBareTree(tree.Nodes)
	fmt.Println("------------------------------------------------------")
	fmt.Println("CST:")
	parser.PrintTree(tree)
	if err != nil {
		var msg = err.Message()
		fmt.Println(msg.RenderConsole(richtext.RenderOptionsConsole {
			AnsiPalette: richtext.DefaultPalette(),
		}))
	} else {
		fmt.Println("------------------------------------------------------")
		fmt.Println("AST:")
		transformer.PrintNode(reflect.ValueOf(transformer.Transform(tree)))
		// fmt.Printf("%+v\n", transformer.Transform(tree))
	}
}


